from django.shortcuts import render_to_response
from django.http import HttpResponse
from svp.warper.models import PlanetRequest
import json


def home(request):
  return render_to_response('index.html')


def create(request, panorama):
  response = {'status': '', 'id': 0};

  try:
    # Check if the panorama has already been requested.
    existing = PlanetRequest.objects.filter(panorama=panorama)

    if not bool(existing):
      # Add panorama to the queue.
      planet_request = PlanetRequest(panorama=panorama)
      planet_request.save()

      # Return new request ID.
      response['status'] = 'waiting'
      response['id'] = planet_request.id
    else:
      # Check if the panorama has already been warped.
      complete = existing.filter(complete=True)

      if bool(complete):
        # It has already been warped!
        response['status'] = 'complete';
        response['id'] = complete[0].id
      else:
        # It has not been warped yet.
        response['status'] = 'waiting';
        response['id'] = existing[0].id
  except ex:
    # An error occured.
    response['status'] = 'error'

  return HttpResponse(json.dumps(response))


def check_status(request, id):
  response = {'status': ''}

  try:
    id = int(id)
  except ValueError, ex:
    response['status'] = 'error'
  else:
    try:
      # Find request with given ID.
      planet_request = PlanetRequest.objects.get(id=id)

      if planet_request.complete:
        # Request has been processed.
        response['status'] = 'complete'
      else:
        # Waiting in queue.
        response['status'] = 'waiting'
    except:
      response['status'] = 'error'

  return HttpResponse(json.dumps(response))

